<template>
  <div class="wxTooltip">
    <div v-if="!showTooltip" @mouseenter="e=>isShowTooltip(e)">
      <div :class="{'single-text':line<2,'line-text':line>1}" :style="{'-webkit-line-clamp':line}">
        <slot></slot>
      </div>
    </div>
    <el-tooltip v-else>
      <template #content>
        <div class="line-tooltip">{{ content }}</div>
      </template>
      <div :class="{'single-text':line<2,'line-text':line>1}" :style="{'-webkit-line-clamp':line}"
           @mouseout="hideToolTip">
        <slot></slot>
      </div>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  name: "wxTooltip",
  props: {
    line: {
      default: 1,
      type: Number
    }
  },
  data() {
    return {
      showTooltip: false,
      content: null
    }
  },
  methods: {
    hideToolTip() {
      this.showTooltip = false
    },
    isShowTooltip(e) {
      const el = e.target
      const bool = this.textRange(el)
      if (bool) {
        let contentDoc = el.children[0].children
        let text = el.innerText
        if (contentDoc.length) {
          text = ''
          for (let i = 0; i < contentDoc.length; i++) {
            text += contentDoc[i].innerText + ' '
          }
        }
        this.content = text
      }
      this.showTooltip = bool
    },
    textRange(el) {
      const textContent = el
      const target = textContent.getBoundingClientRect()
      const range = document.createRange()
      range.setStart(textContent, 0)
      range.setEnd(textContent, textContent.childNodes.length)
      if (this.line > 1) {
        const targetHeight = target.height
        const rangeHeight = range.getBoundingClientRect().height
        // console.debug('多行tooltip 实际高度', rangeHeight, '区域高度：', targetHeight)
        return rangeHeight > targetHeight
      } else {
        const targetW = target.width
        const rangeWidth = range.getBoundingClientRect().width
        // console.debug('单行tooltip 实际宽度', rangeWidth, '区域宽度：', targetW)
        return rangeWidth > targetW
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wxTooltip {
  flex: 1;
}

.line-text {
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  display: -webkit-box;
}

.single-text {
  white-space: nowrap;
  /* 溢出的部分隐藏 */
  overflow: hidden;
  /* 文字溢出的时候用省略号显示 */
  text-overflow: ellipsis;
}

//::v-deep.el-tooltip__popper
.line-tooltip {
  max-width: 30vw;
}
</style>
